from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
import re
import mascaradelatex




def get_img(url):
    # 1. 初始化浏览器驱动（以Chrome为例）
    driver = webdriver.Chrome()  # 需提前安装对应版本驱动
    driver.get(url)  # 替换为目标页面URL

    # 2. 显式等待元素加载（关键步骤）
    try:
        # 根据ID定位元素的等待策略
        element = WebDriverWait(driver, 15).until(
            EC.presence_of_element_located(
                (By.CLASS_NAME, "section-template-15053874790448__main__container")  # 若ID固定则直接写死
            )
        )
    except:
        print("元素加载超时")
        driver.quit()
        exit()
    # 1. 正则表达式提取
    pattern = r'href="([^"]+)"\s+data-info="'
    matches = re.findall(pattern, element.get_attribute("outerHTML"))
    driver.quit()
    return matches

if __name__ == '__main__':
    # 2. 生成完整URL
    base_url = "https://mascaradelatex.com"
    urls = []
    download_folder = mascaradelatex.create_unique_folder()
    print(f"创建下载目录：{download_folder}")
    for path in get_img("https://mascaradelatex.com/collections/one-piece"):
        # 处理相对路径格式
        if not path.startswith('/'):
            path = '/' + path
        full_url = f"{base_url}{path}"
        urls.append(full_url)
        print("生成地址:", full_url)
        # 3. 验证输出
        print("\n最终URL列表：")
        print(urls)
        mascaradelatex.get_img(full_url,download_folder)


